package com.yf.ability.login.dingtalk.utils;


import com.alibaba.fastjson.JSON;
import com.aliyun.dingtalkcontact_1_0.models.GetUserHeaders;
import com.aliyun.dingtalkoauth2_1_0.models.GetUserTokenRequest;
import com.aliyun.dingtalkoauth2_1_0.models.GetUserTokenResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.yf.ability.login.dingtalk.dto.response.DingUserRespDTO;


public class DingUtils {


    public static com.aliyun.dingtalkoauth2_1_0.Client authClient() throws Exception {
        Config config = new Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalkoauth2_1_0.Client(config);
    }

    public static com.aliyun.dingtalkcontact_1_0.Client contactClient() throws Exception {
        Config config = new Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalkcontact_1_0.Client(config);
    }


    /**
     * 用于网站扫码后获得用户信息登录
     * @param authCode
     * @return
     * @throws Exception
     */
    public static DingUserRespDTO snsInfo(String appKey, String secretKey, String authCode) throws Exception {

        GetUserTokenRequest getUserTokenRequest = new GetUserTokenRequest()
                .setClientId(appKey)
                .setClientSecret(secretKey)
                .setCode(authCode)
                .setGrantType("authorization_code");

        com.aliyun.dingtalkoauth2_1_0.Client oauthClient = DingUtils.authClient();
        GetUserTokenResponse getUserTokenResponse = oauthClient.getUserToken(getUserTokenRequest);

        //获取用户个人token
        String token = getUserTokenResponse.getBody().getAccessToken();

        com.aliyun.dingtalkcontact_1_0.Client contactClient = DingUtils.contactClient();
        GetUserHeaders getUserHeaders = new GetUserHeaders();
        getUserHeaders.xAcsDingtalkAccessToken = token;
        //获取用户个人信息，如需获取当前授权人的信息，unionId参数必须传me
        String json = JSON.toJSONString(contactClient.getUserWithOptions("me", getUserHeaders, new RuntimeOptions()).getBody());

        DingUserRespDTO respDTO = JSON.parseObject(json, DingUserRespDTO.class);
        return  respDTO;
    }

}
